package com.luban.security02.config;

import com.luban.security02.handler.MyAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Spring Security授权是怎么做的？
 * 1、继承我们的适配器WebSecurityConfigurerAdapter
 *
 * @author : fujc-dev@qq.com
 * @motto : talk is cheap, show me the code. salute the future!
 */
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)   /*开启方法授权*/
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //需要登录认证
        http.formLogin();

        http.authorizeRequests() //需要经过授权的请求有那些
                //我们系统，可能需要不需要认证的请求
                //.antMatchers("/admin/demo").permitAll()
                //.antMatchers("/admin/demo").hasRole("admin")  针对的是角色的值ROLE_admin

                //.antMatchers("/admin/demo").permitAll() /*permitAll 运行访问*/
                //.antMatchers("/admin/demo").hasIpAddress("127.0.0.1")

                //基于表达式，好处？可以自定义，会涉及到
                //.antMatchers("/admin/demo").access("hasAuthority('admin')")

                //.antMatchers("/user/login").permitAll()

                //隔离，张三、李四、王五都需要访问这个资源的时候，进行资源隔离
                //具体的场景不一定非得是隔离，只是此处的例子是隔离，只有当name是admin的时候，访问正常。
                //.antMatchers("/admin/demo").access("@mySecurityExpression.hasPermission(request,authentication)")
                //所有请求都需要进行认证
                .anyRequest().authenticated();

        //使用 Spring Security 时经常会看见 403（无权限）。
        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());
        //
        http.csrf().disable();
    }
}
